# -*- coding: utf-8 -*-
# Date: 2025-01-02
# Author: HonestQiao
#
# Desc: 天气信息获取

import time
import urequests as requests
import json
import utime

# 城市编号：全局设置 CITY_ID
# city_id = '101010100'

# 天气信息网址
home_url = 'https://zte.weatherol.com/home.html?id='
city_url = 'https://zte.weatherol.com/getCityInfo?id='
aqi_url = 'https://zte.weatherol.com/getAqiforecast24h?id='
rain_url = 'https://zte.weatherol.com/getprecipitationByid?type=forecast&id='
life_url = 'https://zte.weatherol.com/getCurrentIndexDate?stationid='

# header字符串
header_string = '''
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding: identity
Accept-Language: zh,en-US
Cache-Control: no-cache
Connection: keep-alive
Host: zte.weatherol.com
Pragma: no-cache
Referer: https://zte.weatherol.com/
User-Agent: Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36 Edg/127.0.0.0
'''

# 构建header信息
header_dict = {}
for line in header_string.split('\n'):
    if line.strip() == '':
        continue

    key, value = line.split(': ', 1)
    header_dict[key] = value

# 提取信息
def extract_data(start, end, text):
    pos1 = text.find(start) + len(start)
    pos2 = text.find(end)
    return text[pos1:pos2].strip()

# 转换日期信息
def get_date(date_str):
    # 输入的日期时间字符串
    #date_str = "2024-12-25 11:55"

    # 手动解析日期时间字符串
    year, month, day, hour, minute = map(int, date_str.split()[0].split('-') + date_str.split()[1].split(':'))

    # 定义中文星期的映射
    weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

    # 使用utime模块获取星期几的索引
    # utime.mktime将日期时间转换为时间戳
    timestamp = utime.mktime((year, month, day, hour, minute, 0, 0, 0))
    # utime.localtime将时间戳转换为本地时间元组
    local_time = utime.localtime(timestamp)
    # local_time[6]是星期几的索引（0表示星期一，6表示星期日）
    weekday_index = local_time[6]

    # 格式化日期时间字符串
    formatted_date = "{:02d}月{:02d}日".format(
        month, day
    )
    formatted_week = "{}".format(
        weekdays[weekday_index]
    )
    formatted_hm = "{:02d}:{:02d}".format(
        hour, minute
    )

    return [formatted_date,formatted_week,formatted_hm]

# 计算降水量
def get_rain_sum(rain_data):
    return sum(rain_data['result']['minutely']['precipitation_2h'])

# JSON对象
aqi_data = '''
{
    "aqi_ranges": [
        {
            "min": 0,
            "max": 50,
            "description": "优"
        },
        {
            "min": 51,
            "max": 100,
            "description": "良"
        },
        {
            "min": 101,
            "max": 150,
            "description": "轻度"
        },
        {
            "min": 151,
            "max": 200,
            "description": "中度"
        },
        {
            "min": 201,
            "max": 300,
            "description": "重度"
        },
        {
            "min": 301,
            "max": 9999,
            "description": "严重"
        }
    ]
}
'''

# 解析JSON对象
aqi_ranges = json.loads(aqi_data)["aqi_ranges"]

def get_aqi_word(value):
    for range_info in aqi_ranges:
        if range_info["min"] <= int(value) <= range_info["max"]:
            return range_info["description"]
    return "未知"

def get_weather(city_id):
    # 发起请求
    url = f'{home_url}{city_id}'
    print("request url:", url)
    response = requests.get(url, headers=header_dict)
    # print(response.text)

    # 处理信息
    print("process text:")

    # response.text为多行文本，从其中var backstageData=到var loadingtime之间，提取文本
    # 预处理
    response_text = response.text
    while ' =' in response_text or '= ' in response_text:
        response_text = response_text.replace(' =', '=').replace('= ', '=')


    #city_name = extract_data('<span id="cityname">', '</span>', response_text)
    weather_info = extract_data('var backstageData=', 'var loadingtime', response_text)

    # 修复json格式数据
    weather_info_lines = weather_info.split('\n')
    for i, line in enumerate(weather_info_lines):
        if line.startswith(','):
            weather_info_lines[i] = ',\n'+weather_info_lines[i].split(',',1)[1]
        if line.startswith('{'):
            weather_info_lines[i] = '{\n'+weather_info_lines[i].split('{',1)[1]

    weather_info = "\n".join(weather_info_lines)
    weather_info_lines = weather_info.split('\n')

    for i, line in enumerate(weather_info_lines):
        if ':' in weather_info_lines[i]:
            weather_info_lines[i] = '"' + weather_info_lines[i].split(':',1)[0] +  '" : ' + weather_info_lines[i].split(':',1)[1]

    weather_info = "\n".join(weather_info_lines)

    # 解析json数据
    backstageData = json.loads(weather_info)

    liveData = [
        {'name': '湿度', 'pic': 'shidu', 'key': 'humidity', 'value': '', 'unit': '%'},
        {'name': '大气压', 'pic': 'daqiya', 'key': 'airpressure', 'value': '', 'unit': 'hPa'},
        {'name': '能见度', 'pic': 'nengjiandu', 'key': 'visibility', 'value': '', 'unit': 'KM'},
        {'name': '紫外线强度', 'pic': 'ziwaixian', 'key': 'ultravioletrays', 'value': backstageData['ultravioletrays'] if backstageData else '', 'unit': ''},
        {'name': '体感温度', 'pic': 'tigan', 'key': 'feelstemperature', 'value': '', 'unit': '°C'},
        {'name': '风力', 'pic': 'feng', 'key': '', 'value': backstageData['windPowerDecoder'] if backstageData else '', 'unit': ''},
        {'name': '风向', 'pic': 'fengx', 'key': '', 'value': backstageData['windDirDecoder'] if backstageData else '', 'unit': ''},
        {'name': '降水量', 'pic': 'jiangyu', 'key': '', 'value': '', 'unit': 'mm'},
    ]

    liveData_dict = {item['name']: item for item in liveData if item['name']}
    for key in liveData_dict.keys():
        if liveData_dict[key]['key'] != '':
            liveData_dict[key]['value'] = backstageData[liveData_dict[key]['key']]
    #print(json.dumps(liveData_dict))
    #print('backstageData:', json.dumps(backstageData))
    #print('liveData:', json.dumps(liveData))

    # 发起请求
    url = f'{city_url}{city_id}'
    print("request url:", url)
    response = requests.get(url, headers=header_dict)
    #print(response.text)
    cityData = json.loads(response.text)
    #print('airData:', json.dumps(cityData))

    # 发起请求
    url = f'{aqi_url}{city_id}'
    print("request url:", url)
    response = requests.get(url, headers=header_dict)
    #print(response.text)
    airData = json.loads(response.text)
    #print('airData:', json.dumps(airData))

    # 发起请求
    url = f'{rain_url}{city_id}'
    print("request url:", url)
    response = requests.get(url, headers=header_dict)
    #print(response.text)
    rainData = json.loads(response.text)
    #print('rainData:', json.dumps(rainData))

    # 发起请求
    url = f'{life_url}{city_id}'
    print("request url:", url)
    response = requests.get(url, headers=header_dict)
    #print(response.text)
    lifeData = json.loads(response.text)
    #print('rainData:', json.dumps(rainData))

    liveData_dict['降水量']['value'] = get_rain_sum(rainData)
    showData = {
        'city_id': city_id,
        # 左上
        '城市名称': cityData['cityname'],
        '城市图片': 'liveweather/dingwei.png',
        
        # 右上
        '报告时间': get_date(backstageData['reporttime']),
        
        # 左中
        '温度': backstageData['temperature'],
        '天气图片': f"dayweather/{backstageData['weatherPic']}.png",
        '天气类型': backstageData['weatherIndex'],
        '温度范围': "%s°C" % backstageData['lhtemp'],
        
        # 右中
        '风向': backstageData['windDirDecoder'],
        '风力': backstageData['windPowerDecoder'],
        
        '空气质量': "%s%s" %('空气' if len(get_aqi_word(airData[0]['value'])) <= 2 else '', get_aqi_word(airData[0]['value'])),
        '天气预警': backstageData['warninglist'][0]['title'] if len(backstageData['warninglist']) else '',
        '天气预警图片': backstageData['warninglist'][0]['img'] if len(backstageData['warninglist']) else '',
        
        # 底部1排
        '列表': {
            "湿度" : liveData_dict['湿度'],
            "大气压" : liveData_dict['大气压'],
            "能见度" : liveData_dict['能见度'],
            "紫外线强度" : liveData_dict['紫外线强度'],
            
            # 底部2排
            "体感温度" : liveData_dict['体感温度'],
            "风力" : liveData_dict['风力'],
            "风向": liveData_dict['风向'],
            "降水量" : liveData_dict['降水量'],
        },
        '生活指数': lifeData
    }

    return showData
